import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import { baseUrl, getTokenHeader } from "@/utils/auth";

interface CacheData {
  timestamp: number;
  data: any;
}

class AxiosCache {
  private cache: Map<string, CacheData>;
  private axiosInstance: AxiosInstance;

  constructor() {
    this.cache = new Map();
    this.axiosInstance = axios.create({
      timeout: 6000 // 请求超时时间
    });
    this.setupInterceptors();
  }

  // 设置请求拦截器
  private setupInterceptors() {
    this.axiosInstance.interceptors.request.use(
      config => {
        const { params, method, headers } = config;
        // 如果是以 '/' 开头的地址都加上 BaseURL
        let url: string = config.url?.trim() || "";
        if (url.indexOf("/") === 0) {
          url = baseUrl + url;
        }
        config.url = url;

        // 所有的请求都加上 Token
        Object.keys(getTokenHeader()).forEach((key: string) => {
          headers[key] = getTokenHeader()[key];
        });

        if (method === "get") {
          config.params = {
            _t: new Date().getTime(),
            ...params
          };
        }
        return config;
      },
      error => Promise.reject(error)
    );
  }

  // 发送请求并处理缓存
  public async request<T>(config: AxiosRequestConfig): Promise<T> {
    const cacheKey = this.generateCacheKey(config);
    const cacheEntry = this.cache.get(cacheKey);

    if (cacheEntry) {
      const currentTime = new Date().getTime();
      if (currentTime - cacheEntry.timestamp < 60000) {
        // 一分钟内直接返回缓存
        return cacheEntry.data as T;
      }
    }

    const response = await this.axiosInstance.request<T>(config);
    this.cache.set(cacheKey, { timestamp: new Date().getTime(), data: response.data });
    return response.data;
  }

  // 发起 GET 请求
  public async get<T>(url: string, params?: any): Promise<T> {
    return this.request<T>({
      method: "get",
      url,
      params
    });
  }

  // 生成缓存键
  private generateCacheKey(config: AxiosRequestConfig): string {
    return `${config.method}-${config.url}-${JSON.stringify(config.params)}`;
  }
}

const execRemoteAPI = new AxiosCache();

export { execRemoteAPI };
